class SimpleAsyncValidator {
  constructor(rules) {
    this.rules = rules;
  }

  // 校验单个规则
  validateRule(rule, value) {
    return new Promise((resolve, reject) => {
      if (rule.required && (value === undefined || value === null || value === '')) {
        reject(rule.message || 'This field is required');
      } else if (rule.validator) {
        rule.validator(rule, value, (error) => {
          if (error) {
            reject(error);
          } else {
            resolve();
          }
        });
      } else {
        resolve();
      }
    });
  }

  // 校验所有规则
  validate(data) {
    const promises = [];
    Object.keys(this.rules).forEach((field) => {
      const value = data[field];
      const fieldRules = this.rules[field];
      fieldRules.forEach((rule) => {
        promises.push(this.validateRule(rule, value).catch((error) => ({
          field,
          error,
        })));
      });
    });
    return Promise.all(promises).then((results) => {
      const errors = results.filter((result) => result);
      if (errors.length) {
        throw errors;
      }
    });
  }
}

// 使用示例
const validator = new SimpleAsyncValidator({
  username: [
    { required: true, message: 'Username is required' },
    {
      validator: (rule, value, callback) => {
        if (value.length < 6) {
          callback('Username must be at least 6 characters');
        } else {
          callback();
        }
      },
    },
  ],
});

const data = {
  username: 'abc',
};

validator.validate(data).then(() => {
  console.log('Validation passed');
}).catch((errors) => {
  console.log('Validation failed', errors);
});
